package com.team1.system.model;

import okhttp3.*;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.URLEncoder;
import java.nio.file.Paths;
import java.util.Base64;
import javax.sound.sampled.*;

public class SpeechToText {
    public static final String API_KEY = "z54my9uQ8PRLLneUUE6sI2jI";
    public static final String SECRET_KEY = "AY3Onhsx9gTHxPVZttkvkeNN4zRbXA3f";

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    //采样率识别
    public static int toInt(byte[] b) {
        return u(b[15]) * 16777216 + u(b[14]) * 65536 + u(b[13]) * 256 + u(b[12]);
    }

    private static int u(int n) {
        return n & 255;
    }

    public static byte[] read(RandomAccessFile rdf) throws IOException {
        byte[] bytes = new byte[12];
        rdf.read(bytes);
        bytes = new byte[24];
        rdf.read(bytes);
        rdf.close();
        return bytes;
    }



        public static String transform(String before) {
            String sourceFilePath = before;  // 替换为源音频文件路径
            String targetFilePath = "C:\\Users\\16846\\Desktop\\1-16.wav";  // 替换为目标音频文件路径

            try {
                // 读取源音频文件
                AudioInputStream sourceStream = AudioSystem.getAudioInputStream(new java.io.File(sourceFilePath));

                // 获取源音频的格式
                AudioFormat sourceFormat = sourceStream.getFormat();

                // 创建目标音频的格式，降采样到16,000 Hz
                AudioFormat targetFormat = new AudioFormat(16000, sourceFormat.getSampleSizeInBits(), sourceFormat.getChannels(), true, false);

                // 使用AudioSystem将源音频文件转换为目标音频格式
                AudioInputStream targetStream = AudioSystem.getAudioInputStream(targetFormat, sourceStream);

                // 将目标音频保存为文件
                File targetFile = new File(targetFilePath);
                AudioSystem.write(targetStream, AudioFileFormat.Type.WAVE, targetFile);

                // 关闭输入输出流
                sourceStream.close();
                targetStream.close();

                System.out.println("音频降采样完成！");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return targetFilePath;
        }



    public static void main(String []args) throws IOException {
        //将音频降采样为16000
        String path = transform("C:\\Users\\16846\\Desktop\\1.wav");
        //读取音频的采样率rating以及字节数byteCount
        File f = new File(path);
        RandomAccessFile rdf = null;
        rdf = new RandomAccessFile(f,"r");
        long byteCount = Files.size(f.toPath());
        //System.out.println(byteCount);
        int rating = toInt(read(rdf));
        //System.out.println(rating);

        rdf.close();

        String base64 = getFileContentAsBase64(path,false);

        MediaType mediaType = MediaType.parse("application/json");
        // speech 可以通过 getFileContentAsBase64("C:\fakepath\000001.wav") 方法获取,如果Content-Type是application/x-www-form-urlencoded时,第二个参数传true
        RequestBody body = RequestBody.create(mediaType, "{\"format\":\"wav\",\"rate\":"+rating+",\"channel\":1,\"cuid\":\"111\",\"token\":\"\",\"speech\":\""+base64+"\",\"len\":" + byteCount + ",\"token\":\"" + getAccessToken() + "\"}");
        Request request = new Request.Builder()
                .url("https://vop.baidu.com/server_api")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        System.out.println(response.body().string());

    }

    /**
     * 获取文件base64编码
     *
     * @param path      文件路径
     * @param urlEncode 如果Content-Type是application/x-www-form-urlencoded时,传true
     * @return base64编码信息，不带文件头
     * @throws IOException IO异常
     */
    static String getFileContentAsBase64(String path, boolean urlEncode) throws IOException {
        byte[] b = Files.readAllBytes(Paths.get(path));
        String base64 = Base64.getEncoder().encodeToString(b);
        if (urlEncode) {
            base64 = URLEncoder.encode(base64, "utf-8");
        }
        return base64;
    }


    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    static String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        try {
            return new JSONObject(response.body().string()).getString("access_token");
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }

}
